package com.zrrd.network.chatRoom;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author WanJl
 * @version 1.0
 * @title Client
 * @description
 * @create 2023/11/5 9:16
 */
public class Client {
    public void start()throws IOException{
        System.out.println("正在连接服务器...");
        //1、创建Socket对象
        Socket socket = new Socket("127.0.0.1", 10010);
        System.out.println("已经和服务器建立连接...");
        //2、先输入用户名
        Scanner sc = new Scanner(System.in);
        String username = null;
        while (true) {
            System.out.println("请输入用户名..");
            username = sc.nextLine();
            //去掉开头和结尾的空格
            username = username.trim();
            if (username.length() > 0) {
                break;
            }
            System.out.println("输入有误");
        }
        System.out.println("欢迎你" + username + "！开始聊天吧");

        //通过socket对象获取输出流
        OutputStream out = socket.getOutputStream();
        OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8");
        PrintWriter pw = new PrintWriter(osw, true);
        //先把用户名发送给服务器
        pw.println(username);

        //再读取来自服务器端发送的消息
        ServerHandler handler = new ServerHandler(socket);
        Thread thread = new Thread(handler);
        thread.start();

        //在发送消息
        while (true) {

            pw.println(sc.nextLine());

        }
    }



    public void receiveMsg(Socket socket) {

    }

}




























